package cn.virens.web.components.shiro.simple.simple;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.hutool.core.util.ObjectUtil;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.web.components.shiro.ShiroAuthInterface;
import cn.virens.web.components.shiro.comm.SessionUtil;

/**
 * 打印请求地址
 * 
 * @author virens
 */
public class SimpleUserFilter extends UserFilter {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	@Qualifier(ShiroAuthInterface.SHIRO_BEAN_NAME)
	protected ShiroAuthInterface shiroAuthInterface;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		logger.debug(((HttpServletRequest) request).getRequestURI());

		// 如果是登陆请求就放行
		if (isLoginRequest(request, response)) return true;

		// 获取认证令牌
		Subject subject = getSubject(request, response);
		if (subject == null) return false;

		// 获取当前登陆用户 & 获取当前用户的session
		Object principal = subject.getPrincipal();
		Session session = subject.getSession(false);
		if (principal != null && session != null) {
			checkSession(session, principal);
		} else {
			return false;
		}

		return true;
	}

	protected void checkSession(Session session, Object principal) {
		SysUser sessionUserInfo = SessionUtil.getUserInfo(session);
		String sessionGroups = SessionUtil.getGroupKeys(session);
		String sessionRoles = SessionUtil.getRoleKeys(session);
		String sessionUuid = SessionUtil.getUserUuid(session);

		// 如果登录用户的用户信息OR角色信息为空，就通过对应接口获取
		if (!ObjectUtil.isAllNotEmpty(sessionUserInfo, sessionUuid, sessionRoles, sessionGroups)) {
			SessionUtil.saveLoginInfo2(session, shiroAuthInterface.getGroups(principal));
			SessionUtil.saveLoginInfo1(session, shiroAuthInterface.getRoles(principal));
			SessionUtil.saveLoginInfo0(session, shiroAuthInterface.getUser(principal));
		}
	}
}
